#!/usr/bin/ruby -w

require 'net/telnet.rb'

class Net::Telnet
  def rawcmd(options) # :yield: recvdata
	match    = @options["Prompt"]
	time_out = @options["Timeout"]

	if options.kind_of?(Hash)
	  string   = options["String"]
	  match    = options["Match"]   if options.has_key?("Match")
	  time_out = options["Timeout"] if options.has_key?("Timeout")
	else
	  string = options
	end

	#here's the only difference from the original cmd method: use print instead of puts
	#puts will add a "\n" character at the end of the string, print won't
	self.print(string)
	if block_given?
	  waitfor({"Prompt" => match, "Timeout" => time_out}){|c| yield c }
	else
	  waitfor({"Prompt" => match, "Timeout" => time_out})
	end
  end
end

class BBS
  attr_reader :address_book

  def initialize
	@address_book = {}
	addBBS("88", "bbs88.8800.org", 10000, "binaryxie", "hanjian@")
	addBBS("drangon", "drangon.3322.org", 8888, "binaryxie", "hanjian@")
	addBBS("lqqm", "lqqm.net", 23, "flowerborn", "hanjian")

	#login prompt pattern
	@username_prompt = /\):[ ]*\z/
	@password_prompt = /:/
	@general_prompt = /[.]{3}/
  end

  def connect(*args)
	if args.size == 1
	  address = @address_book[args[0]]
	  puts "connecting " + args[0] + " ..."
	  @bbs = Net::Telnet::new("Host" => address["Host"],
							  "Port" => address["Port"],
							  "Timeout" => 30,
							  "Prompt" => @general_prompt,
							  "Output_log" => "log.txt")
	  account = {"Name" => address["Username"],
				  "Password" => address["Password"],
				  "LoginPrompt" => @username_prompt,
				  "PasswordPrompt" => @password_prompt}
	  @bbs.login(account) {|c| print c}
	elsif args.sizea == 4
	else
	  throw "This method need either 1 or 4 parameters."
	end
  end

  def act(action, prompt=@general_prompt)
	act = {"String" => action, "Match" => prompt}
	@bbs.rawcmd(act) {|c| print c}
  end

  def post()
  end

  def logout()
	puts "login out ..."
	@bbs.close
  end

  def addBBS(name, host, port, username, password)
	newBBS = {"Host" => host, "Port" => port,
			  "Username" => username, "Password" => password}
	@address_book[name] = newBBS	
  end

  def delBBS(name)
	@address_book[name] = nil
  end

end

